/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: shentong
 * @LastEditTime: 2022-02-24 21:47:33
 */

// eslint-disable-next-line @typescript-eslint/no-use-before-define
import React, { useEffect, useState, useCallback, useReducer, useRef } from "react";
import Taro, { useReachBottom, usePullDownRefresh, useDidShow, useRouter } from '@tarojs/taro'

import { connect } from 'react-redux'

import { AtNoticebar } from 'taro-ui'

import { View } from "@tarojs/components";
import { getAddressPage, delAddress } from '@/api/user'
import { AtIcon } from 'taro-ui'

import NoDataIcon from '@/src/assets/icon/noDataIcon.png'
import AddressItem from "@/src/components/custom/addressItem";
import NoMore from "@/components/custom/no-more";
import Confirm from '@/components/custom/confirm';


import styles from './index.module.scss'

const listReducer = (state, action) => {
  switch (action.type) {
    case 'init': return action.payload
    case 'concat': return state.concat(action.payload)
    default: return state
  }
}

const Myaddress = (props) => {
  const { dispatch } = props

  const [pageNo, setPageNo] = useState(1);
  const [pageSize] = useState(10);
  const [showSkeleton, setShowSkeleton] = useState<boolean>(true)
  const [addressList, localDispatch] = useReducer(listReducer, [])
  const [isLoadFinish, setIsloadFinish] = useState(false)
  /** 侧滑删除 */
  const [curMoveIndex, setMoveIndex] = useState<number>(-1)
  // 删除某一条语音模态框
  const [delVoiceConfirm, setDelVoiceConfirm] = useState<boolean>(false)
  // 当前需要删除的一项
  const [curDelItem, setCurItem] = useState<any>(null)

  // 一些全局的变量 ：显示骨架屏
  const showSkeletonRef =  useRef(true);

  const routerParams = useRouter().params;

  const getAddressList = useCallback(() => {
    if(!showSkeletonRef.current) Taro.showLoading({ title: "加载中...", mask: true });

    const params = { pageSize, pageNo}
    getAddressPage(params).then(res => {
      const { data: { records = [], lastPage } = {} } = res

      setIsloadFinish(lastPage)

      const actionType = pageNo === 1 ? 'init' : 'concat'
      localDispatch({ type: actionType, payload: records })

      Taro.hideLoading();
    }).finally(() => {
      setShowSkeleton(false)
      showSkeletonRef.current = false
      Taro.stopPullDownRefresh();
    })
  }, [localDispatch, pageNo, pageSize])

  const newAddress = (item) => {
    dispatch({ type: 'NEWADDRESS', payload: {
      address: item.address || '',
      cellPhone: item.cellPhone || '',
      detailAdd: item.detailAdd || '',
      gender: item.gender,
      userName: item.userName || '',
      lat: item.lat || '',
      lon: item.lon || '',
      addressId: item.addressSId || '',
      deliveryFloor: item.deliveryFloor || ''
    }})
  }

  const itemClick = (item => {
    if (routerParams.from === 'submitOrder') {
      newAddress(item)
      Taro.navigateBack()
    }
  })

  const editClickHandle = (item => {
    newAddress(item)

    Taro.navigateTo({
      url: `/pages/addAddress/index?isEdit=1`,
      success: () => setTimeout(()=> { setMoveIndex(-1) }, 1000)
    });
  })

  /**
   * @description 点击删除按钮
   * @param itemData 当前点击项
   */
    const delClickHanle = (itemData) => {
    setCurItem(itemData)
    setDelVoiceConfirm(true)
  }
  /* 确认删除 */
  const confirmDel = () => {
    const { addressSId } = curDelItem
    if (addressSId) {
      Taro.showLoading({ title: "加载中...", mask: true });
      delAddress({ addressId: addressSId }).then(() => {
        delArrByIndex(addressSId)

        Taro.hideLoading()
      })
    }
  }

  /**
   * @description 通过id查找数组中某一个，并删除
   */
    const delArrByIndex = (addressSId) => {
      const findIndexById = addressList.findIndex((item) => item.addressSId === addressSId)
      addressList.splice(findIndexById, 1)

      localDispatch({ type: 'init', payload: addressList })
      setMoveIndex(-1)
      setCurItem(null)
      setDelVoiceConfirm(false)
    }

   /** 关闭模态框 */
   const closeModal = () => {
    setDelVoiceConfirm(false)

    setMoveIndex(-1)
  }

  const addAddressHandel = () => {
    Taro.navigateTo({url: '/pages/addAddress/index'})
  }

    /**
   * @description 侧滑事件
   * @param moveIndex 侧滑当前项对应的index
   */
     const touchMoveHandle =  (moveIndex) => setMoveIndex(moveIndex)

  useDidShow(() => {
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    Taro.startPullDownRefresh()
  })

  useEffect(() => {
    if(!showSkeletonRef.current) getAddressList()
  }, [getAddressList])

  // 下拉刷新
  usePullDownRefresh(() => {
    if (pageNo !== 1)  setPageNo(1);
    else getAddressList()
  });

  useReachBottom(() => {
    !isLoadFinish && setPageNo(pageNo + 1)
  })

  // const propsBar = <View><AtIcon value='edit' size='24' color='#50bafe'></AtIcon></View>

  return (
    <View className={styles.myaddress}>
      { addressList.length ? <AtNoticebar>侧滑可编辑、删除地址~</AtNoticebar> : null}
      <View className={styles.listBox}>
        {/* 商品列表+骨架屏 */}
        <van-skeleton title row='6' loading={showSkeleton}>
          {
            addressList.map((item, index) => {
              return (
              <View className={styles.itemBox} key={index}>
                <AddressItem
                  index={index}
                  dataItem={item}
                  detail={item.detail}
                  curMoveIndex={curMoveIndex}
                  touchMoveFn={touchMoveHandle}
                  address={item.address}
                  cellPhone={item.cellPhone}
                  gender={item.gender}
                  userName={item.userName}
                  clickHandle={() => itemClick(item)}
                  editClick={() => editClickHandle(item)}
                  delClick={() => delClickHanle(item)}
                />
              </View>
              )
            })
          }

          {addressList.length && isLoadFinish ? <NoMore /> : null}
        </van-skeleton>
      </View>
       {/* 暂无数据 */}
       {
         !showSkeleton && !addressList.length && (
          <van-empty description='暂无数据' image={NoDataIcon} />
         )
       }

       {/* 删除某一条、取消、确认 模态框 */}
        {
          delVoiceConfirm && <Confirm
            onClose={closeModal}
            onConfirm={confirmDel}
            title='删除当前地址？'
            cancelTxt='取消'
            confirmTxt='确认'
            ctxTxt='删除后将无法再使用此地址'
          />
        }

      <View className={styles.operateBtn} onClick={addAddressHandel}>
        <View className={styles.addBtn}>新增地址</View>
      </View>
    </View>
  );
}

export default connect((null), dispatch => ({
  dispatch
}))(Myaddress)
